package com.itheima.web.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception4project.CheckGroupDeleteFailException;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/checkGroup")
public class CheckGroupController {

    @Reference
    private CheckGroupService checkGroupService;

    @PostMapping("/add")
    public Result add(@RequestBody CheckGroup checkGroup, Integer[] checkitemsIds) {

        try {
            checkGroupService.add(checkGroup, checkitemsIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
    }

    @PostMapping("/pageHelper")
    public PageResult pageHelper(@RequestBody QueryPageBean queryPageBean) {
        return checkGroupService.get4Page(queryPageBean);
    }

    @PostMapping("/update")
    public Result updateCheckGroup(@RequestBody CheckGroup checkGroup, Integer[] checkitemsIds) {
        try {
            checkGroupService.updateCheckCroup(checkGroup, checkitemsIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS);
    }

    @GetMapping("/delete")
    public Result deleteCheckGroup(Integer id) {

        try {
            checkGroupService.deleteCheckGroup(id);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof CheckGroupDeleteFailException)
                return new Result(false, "当前检查项与套餐存在关联关系，请删除关联套餐后再进行操作！");
            else
                return new Result(false, MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_CHECKGROUP_SUCCESS);
    }

    @PostMapping("/findCheckItemIds")
    public List<Integer> findCheckItemIds(Integer id) {
        return checkGroupService.findCheckItemIds(id);
    }

    @PostMapping("/checkItemPageHelper")
    public PageResult findCheckItemPageHelper(@RequestBody QueryPageBean queryPageBean, Integer[] checkitemIds) {
        return checkGroupService.findCheckItemPageHelper(queryPageBean, checkitemIds);
    }
}